# Copyright (C) 2018-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#

if(ENABLE_CLANG_TIDY)
    set(CLANG_TIDY_REQUIRED_VERSION 18 CACHE STRING "clang-tidy version to use")
    set(CLANG_TIDY_FILENAME clang-tidy-${CLANG_TIDY_REQUIRED_VERSION} clang-tidy)
    find_host_program(CLANG_TIDY NAMES ${CLANG_TIDY_FILENAME} PATHS ENV PATH)
    message(STATUS "Found clang-tidy: ${CLANG_TIDY}")
    if(CLANG_TIDY)
        execute_process(COMMAND ${CLANG_TIDY} ${CMAKE_CURRENT_SOURCE_DIR} ARGS --version OUTPUT_VARIABLE CLANG_VERSION)
        if(NOT CLANG_VERSION)
            message(FATAL_ERROR "Supported clang-tidy version is ${CLANG_TIDY_REQUIRED_VERSION}!")
        else()
            string(REGEX REPLACE "[^0-9]+([0-9]+)\\..*" "\\1" CLANG_TIDY_MAJOR_VERSION ${CLANG_VERSION})
            if(NOT CLANG_TIDY_MAJOR_VERSION EQUAL CLANG_TIDY_REQUIRED_VERSION)
                message(FATAL_ERROR "Supported clang-tidy version is ${CLANG_TIDY_REQUIRED_VERSION}! Provided version ${CLANG_TIDY_MAJOR_VERSION}")
            endif()
        endif()
    else()
        message(FATAL_ERROR "Supported clang-tidy-${CLANG_TIDY_REQUIRED_VERSION} is not found!")
    endif()
endif()

#
# ov_apply_clang_tidy(TARGET <target_name> [EXCLUDE_RISCV64])
#
# Applies clang-tidy configuration to a target with unified options
#
function(ov_apply_clang_tidy)
    include(CMakeParseArguments)
    cmake_parse_arguments(TIDY "EXCLUDE_RISCV64" "TARGET" "" ${ARGN})
    if(NOT TIDY_TARGET)
        message(FATAL_ERROR "TARGET is required for ov_apply_clang_tidy")
    endif()
    if(NOT ENABLE_CLANG_TIDY)
        return()
    endif()
    if(TIDY_EXCLUDE_RISCV64 AND RISCV64)
        return()
    endif()
    set(clang_tidy_options "--extra-arg=-Wno-unused-command-line-argument")
    list(APPEND clang_tidy_options "--extra-arg=-Wno-unknown-warning-option")
    if(DEFINED CMAKE_CXX_COMPILER_TARGET)
        list(APPEND clang_tidy_options "--extra-arg=--target=${CMAKE_CXX_COMPILER_TARGET}")
    endif()
    if(DEFINED OV_CLANG_TIDY_TOOLCHAIN_FLAGS)
        list(APPEND clang_tidy_options ${OV_CLANG_TIDY_TOOLCHAIN_FLAGS})
    endif()
    if(ENABLE_CLANG_TIDY_FIX)
        list(APPEND clang_tidy_options "--fix")
    endif()
    if(RISCV64)
        list(APPEND clang_tidy_options "--extra-arg-before=-march=rv64gcv1p0_zfh")
        list(APPEND clang_tidy_options "--extra-arg-before=-mabi=lp64d")
        list(APPEND clang_tidy_options "--extra-arg-before=-D__fp16=_Float16")
    endif()
    set_target_properties(${TIDY_TARGET} PROPERTIES
        CXX_CLANG_TIDY "${CLANG_TIDY};${clang_tidy_options}")
endfunction()
